#include <string>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
};

class Solution
{
public:
    void s(TreeNode* root, string& str)
    {
        if (root == nullptr)
        {
            return;
        }

        str += to_string(root->val);

        if (root->left)
        {
            str += "(";
            s(root->left, str);
            str += ")";
        }
        else if (root->right)
        {
            str += "()";
        }

        if (root->right)
        {
            str += "(";
            s(root->right, str);
            str += ")";
        }
    }

    string tree2str(TreeNode *root)
    {
        string str;
        s(root, str);
        return str;
    }
};
